package com.stackoverflow.answer;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.sling.api.resource.ResourceResolver;

//TODO change name of project to reflect the purpose and content
public class PlainTextFileReader {

	/**
	 * http://stackoverflow.com/questions/16932789/accessing-resource-data-from-jcr-repo
	 * 
	 * @throws RepositoryException
	 * @throws IOException
	 * 
	 */
	public void read(ResourceResolver resourceResolver) throws RepositoryException, IOException {
		Session session = resourceResolver.adaptTo(Session.class);
		Node root = session.getRootNode();
		Node jcrContent = root.getNode("testNode/A/test.txt/jcr:content");

		InputStream is = jcrContent.getProperty("jcr:data").getBinary().getStream();

		BufferedInputStream bis = new BufferedInputStream(is);
		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		int result = bis.read();
		while (result != -1) {
			byte b = (byte) result;
			buf.write(b);
			result = bis.read();
		}
		bis.close();

		System.out.println("plain text: " + buf.toString());
	}

}
